package com.qf.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Ypl
 * @version V1.0
 * @Project September-mavens
 * @Package com.qf.serviceimpl
 * @Description:
 * @Date 2022/10/13 17:46
 */
@SuppressWarnings("all")
@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {

    @Autowired
    DtsPermissionMapper dtsPermissionMapper;

    @Override
    public Set<String> finfPsmByIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
            //条件
        wrapper.in(DtsPermission::getRoleId,roleIds);
        wrapper.in(DtsPermission::getDeleted,false);

        List<DtsPermission> permissionsList = dtsPermissionMapper.selectList(wrapper);

        Set<String> collect = permissionsList.stream().map(permissions -> {
            return permissions.getPermission();
        }).collect(Collectors.toSet());

        return collect;
    }

    /**
     * 修改权限
     */
    @Override
    public void updatePermission(int roleId, List<String> permissions) {
        //根据角色Id查询到该角色所有的权限，然后全部删除
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsPermission::getRoleId,roleId);
        dtsPermissionMapper.delete(wrapper);

        //将新的权限授权与这个角色
        if(permissions !=null && permissions.size()>0){
            for (String permission : permissions) {
                DtsPermission dtsPermission = new DtsPermission();

                dtsPermission.setRoleId(roleId);
                dtsPermission.setDeleted(false);
                dtsPermission.setAddTime(new Date());
                dtsPermission.setUpdateTime(new Date());
                dtsPermission.setPermission(permission);

                dtsPermissionMapper.insert(dtsPermission);
            }
        }
    }
}
